package com.xoa.service.schedule.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.model.nccloud.*;
import com.xoa.service.nccloud.*;
import com.xoa.service.schedule.ScheduledSyncTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ScheduledSyncTaskServiceImpl implements ScheduledSyncTaskService {
    // NCC 接口操作类
    @Autowired
    private INCCloudService nccloudService;

    //NCC 接口日志操作类
    @Autowired
    INCCInterFaceLogService logService;

    //NCC 视图操作类
    @Autowired
    INCCViewService viewService;

    @Autowired
    NccPostVService nccPostVService;

    @Autowired
    NccPsnclVService nccPsnclVService;
    @Autowired
    BdPsndocZzVService bdPsndocZzVService;
    @Autowired
    INCCPsndocService psndocService;

    @Autowired
    NccPostseriesVService nccPostseriesVService;

    private static SimpleDateFormat sdf1 = new SimpleDateFormat(
            "yyyy-MM-dd");
    @Override
    @Scheduled(cron = "0 0 4 * * ?")
    public void defdoc() throws Exception {
        List<String> list = new ArrayList<>();
        list.add("hr_bd_defdoc_xzjb_v");
        list.add("hr_bd_defdoc_rzlx_v");
        list.add("hr_bd_defdoc_rzfs_v");
        list.add("bd_defdoc_ydyy_v");
        for (String a : list) {
            try {

                String requstBody = "{\"view\":\"" + a + "\"}";
                int add = 0;
                String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (resultJson.getIntValue("code") == 1) {

                    if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {
                        if ("bd_defdoc_ydyy_v".equals(a)) {
                            a = "hr_" + a;
                        }
                        String tableName=a.replace("hr","ncc");
                        viewService.truncateTable(tableName);
                        Map<String, Object> psnMap = new HashMap<>();
                        JSONArray dataArray = resultJson.getJSONArray("data");
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject jsonObject = dataArray.getJSONObject(i);

                            BaseBdDefdoc defdoc = new BaseBdDefdoc();
                            defdoc.setCode(jsonObject.getString("code"));
                            defdoc.setName(jsonObject.getString("name"));
                            defdoc.setPkDefdoc(jsonObject.getString("pk_defdoc"));
                            defdoc.setTableNme(tableName);
                            viewService.saveDefdoc(defdoc);
                            add++;
                        }
                    } else {
                        throw new RuntimeException("请求NC视图data-null");
                    }
                } else {
                    throw new RuntimeException(resultJson.getString("message"));
                }
                // 接口调用日志保存
                NCCInterfaceLog ncclog = new NCCInterfaceLog();
                ncclog.setBusinessNo(a);
                ncclog.setContent(requstBody);
                ncclog.setName("视图" + a + "成功清空并添加" + add);
                ncclog.setResultLong(result);
                ncclog.setState("1");
                ncclog.setDisposeState("0");
                logService.save(ncclog);


            } catch (Exception e) {
                System.out.println("视图添加" + a + "失败");
                e.printStackTrace();
                // 接口调用日志保存
                NCCInterfaceLog ncclog = new NCCInterfaceLog();
                ncclog.setBusinessNo(a);
                ncclog.setContent("");
                ncclog.setName("视图添加" + a + "失败");
                ncclog.setResultLong(e.getMessage());
                ncclog.setState("0");
                ncclog.setDisposeState("0");
                logService.save(ncclog);
                System.out.println("视图添加" + a + "" + e.getMessage());
            }
        }

    }

    @Override
    @Scheduled(cron = "0 1 4 * * ?")
    public void hr_om_job_v() throws Exception {
        try {
            String requstBody = "{\"view\":\"hr_om_job_v\"}";
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            int add = 0;
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.getIntValue("code") == 1) {
                if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {
                    viewService.truncateTable("ncc_om_job_v");
                    Map<String, Object> psnMap = new HashMap<>();
                    JSONArray dataArray = resultJson.getJSONArray("data");
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);

                        NccOmJobV job = new NccOmJobV();
                        job.setPkJob(jsonObject.getString("pk_job"));
                        job.setJobcode(jsonObject.getString("jobcode"));
                        job.setJobname(jsonObject.getString("jobname"));
                        job.setPkOrg(jsonObject.getString("pk_org"));
                        job.setPkJobtype(jsonObject.getString("pk_jobtype"));
                        viewService.saveOmJob(job);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(resultJson.getString("message"));
            }

            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_om_job_v");
            ncclog.setContent(requstBody);
            ncclog.setName("职务视图成功清空并添加：" + add);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("职务视图添加false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_om_job_v");
            ncclog.setContent("");
            ncclog.setName("职务视图添加false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }

    @Override
    @Scheduled(cron = "0 2 4 * * ?")
    public void hr_om_jobtype_v() throws Exception {
        try {
            String requstBody = "{\"view\":\"hr_om_jobtype_v\"}";
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);

            int add = 0;
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.getIntValue("code") == 1) {
                if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {
                    viewService.truncateTable("ncc_om_jobtype_v");
                    Map<String, Object> psnMap = new HashMap<>();
                    JSONArray dataArray = resultJson.getJSONArray("data");
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);

                        NccOmJobtypeV job = new NccOmJobtypeV();
                        job.setFatherPk(jsonObject.getString("father_pk"));
                        job.setJobtypecode(jsonObject.getString("jobtypecode"));
                        job.setJobtypename(jsonObject.getString("jobtypename"));
                        job.setPkOrg(jsonObject.getString("pk_org"));
                        job.setPkJobtype(jsonObject.getString("pk_jobtype"));
                        viewService.saveOmJobType(job);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(resultJson.getString("message"));
            }
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_om_jobtype_v");
            ncclog.setContent(requstBody);
            ncclog.setName("职务类别视图成功清空并添加" + add);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("职务类别视图false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_om_jobtype_v");
            ncclog.setContent("");
            ncclog.setName("职务类别视图false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);
        }
    }

    @Override
    @Scheduled(cron = "0 3 4 * * ?")
    public void waprmlv() throws Exception {
        try {
            //薪级
            String requstBody = "{\"view\":\"hr_wa_prmlv_v\"}";
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            JSONObject resultJson = JSONObject.parseObject(result);

            //薪资标准类别
            String requstBody2 = "{\"view\":\"hr_wa_grade_v\"}";
            String result2 = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody2);
            JSONObject resultJson2 = JSONObject.parseObject(result2);

            int add = 0;


            if (resultJson.getIntValue("code") == 1) {
                if (resultJson2.getIntValue("code") == 1) {
                    if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {
                        if (null != resultJson2.getJSONArray("data").toJSONString() && !resultJson2.getJSONArray("data").toJSONString().equals("[]")) {
                            viewService.truncateTable("ncc_wa_prmlv_v");
                            Map<String, Object> psnMap = new HashMap<>();
                            JSONArray dataArray = resultJson.getJSONArray("data");
                            JSONArray dataArray2 = resultJson2.getJSONArray("data");

                            for (int i = 0; i < dataArray.size(); i++) {
                                JSONObject jsonObject = dataArray.getJSONObject(i);

                                for (int a = 0; a < dataArray2.size(); a++) {
                                    if (dataArray2.getJSONObject(a).getString("pk_wa_grd").equals(jsonObject.getString("pk_wa_grd"))) {
                                        NccWaPrmlvV obj = new NccWaPrmlvV();
                                        obj.setPkWaSeclv(jsonObject.getString("pk_wa_seclv"));
                                        obj.setPkWaCrt(jsonObject.getString("pk_wa_crt"));
                                        obj.setPkWaGrd(jsonObject.getString("pk_wa_grd"));
                                        obj.setGrdname(jsonObject.getString("grdname"));
                                        obj.setPrmlvname(jsonObject.getString("prmlvname"));
                                        obj.setPkWaGradever(jsonObject.getString("pk_wa_gradever"));
                                        obj.setSeclvname(jsonObject.getString("seclvname"));
                                        obj.setPkWaPrmlv(jsonObject.getString("pk_wa_prmlv"));
                                        obj.setCriterionvalue(jsonObject.getString("criterionvalue"));
                                        obj.setPkOrg(dataArray2.getJSONObject(a).getString("pk_org"));


                                        viewService.saveWaprmlv(obj);
                                        add++;
                                        break;
                                    }
                                }
                            }
                        } else {
                            throw new RuntimeException("请求NChr_wa_grade_v视图data-null");
                        }
                    } else {
                        throw new RuntimeException("请求NChr_wa_prmlv_v视图data-null");
                    }
                } else {
                    throw new RuntimeException("hr_wa_grade_v:" + resultJson.getString("message"));
                }
            } else {
                throw new RuntimeException("hr_wa_prmlv_v:" + resultJson.getString("message"));
            }

            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("ncc_wa_prmlv_v");
            ncclog.setContent(requstBody);
            ncclog.setName("薪资级别视图成功清空并添加" + add);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("薪资级别视图添加false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("ncc_wa_prmlv_v");
            ncclog.setContent("");
            ncclog.setName("薪资级别视图添加false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }

    @Override
    @Scheduled(cron = "0 4 4 * * ?")
    public void wagrade() throws Exception {
        try {
            String requstBody = "{\"view\":\"hr_wa_grade_v\"}";
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            int add = 0;
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.getIntValue("code") == 1) {
                if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {
                    viewService.truncateTable("ncc_wa_grade_v");
                    Map<String, Object> psnMap = new HashMap<>();
                    JSONArray dataArray = resultJson.getJSONArray("data");
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);
                        NccWaGradeV obj = new NccWaGradeV();
                        obj.setName(jsonObject.getString("name"));
                        obj.setPkWaGrd(jsonObject.getString("pk_wa_grd"));
                        obj.setCode(jsonObject.getString("code"));
                        obj.setPkWaItem(jsonObject.getString("pk_wa_item"));
                        obj.setPkOrg(jsonObject.getString("pk_org"));
                        viewService.saveWaGrad(obj);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(resultJson.getString("message"));
            }

            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_wa_grade_v");
            ncclog.setContent(requstBody);
            ncclog.setName("薪资标准类别视图成功清空并添加" + add);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("薪资标准类别视图添加false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_wa_grade_v");
            ncclog.setContent("");
            ncclog.setName("薪资标准类别视图添加false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }

    @Override
    @Scheduled(cron = "0 5 4 * * ?")
    public void waitem() throws Exception {
        try {
            String requstBody = "{\"view\":\"hr_wa_item_v\"}";
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);

            int add = 0;
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.getIntValue("code") == 1) {
                if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {
                    viewService.truncateTable("ncc_wa_item_v");
                    Map<String, Object> psnMap = new HashMap<>();
                    JSONArray dataArray = resultJson.getJSONArray("data");
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);
                        NccWaItemV obj = new NccWaItemV();
                        obj.setName(jsonObject.getString("name"));
                        obj.setCode(jsonObject.getString("code"));
                        obj.setPkWaItem(jsonObject.getString("pk_wa_item"));
                        obj.setPkOrg(jsonObject.getString("pk_org"));
                        viewService.saveWaItem(obj);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(resultJson.getString("message"));
            }

            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_wa_item_v");
            ncclog.setContent(requstBody);
            ncclog.setName("公共薪资项目视图成功清空并添加" + add);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("公共薪资项目视图添加fasle");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_wa_item_v");
            ncclog.setContent("");
            ncclog.setName("公共薪资项目视图添加fasle");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }

    @Override
    @Scheduled(cron = "0 6 4 * * ?")
    public void trnstype() throws Exception {
        try {
            //请求获取数据
            String requstBody = "{\"view\":\"hr_trnstype_v\"}";
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);

            int add = 0;
            //将数据封装JSON
            JSONObject resultJson = JSONObject.parseObject(result);

            //是否成功
            if (resultJson.getIntValue("code") == 1) {
                if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {

                    //清空表
                    viewService.truncateTable("ncc_trnstype_v");

                    //封装data数据为json数组
                    JSONArray dataArray = resultJson.getJSONArray("data");

                    //遍历数组添加数据库
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jsonObject = dataArray.getJSONObject(i);

                        NccTrnstypeV obj = new NccTrnstypeV();
                        obj.setPkTrnstype(jsonObject.getString("pk_trnstype"));
                        obj.setTrnsevent(jsonObject.getString("trnsevent"));
                        obj.setTrnstypecode(jsonObject.getString("trnstypecode"));
                        obj.setTrnstypename(jsonObject.getString("trnstypename"));
                        viewService.saveTrnstype(obj);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(resultJson.getString("message"));
            }

            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_trnstype_v");
            ncclog.setContent(requstBody);
            ncclog.setName("异动类型视图成功清空并添加" + add);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("异动类型视图添加false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_trnstype_v");
            ncclog.setContent("");
            ncclog.setName("异动类型视图添加false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }

    @Override
    @Scheduled(cron = "0 7 4 * * ?")
    public void hrpostv() throws Exception {
        try {
            //=====1、请求地址获取岗位
            String requstBody = "{\"view\":\"hr_post_v\"}";

            String orgResult = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            JSONArray orgResultJsonArray = JSON.parseObject(orgResult).getJSONArray("data");

            int add = 0, modify = 0, del = 0;
            if (JSON.parseObject(orgResult).getIntValue("code") == 1) {
                if (null != orgResultJsonArray.toJSONString() && !orgResultJsonArray.toJSONString().equals("[]")) {

                    //清空表
                    viewService.truncateTable("ncc_post_v");
                    /*List<NccPostV> psninfoList = nccPostVService.getNccPostVListByMap(null);
                    Map<String, Object> psnMap = new HashMap<>();
                    if (null != psninfoList && psninfoList.size() != 0) {
                        for (NccPostV psninfo : psninfoList) {
                            psnMap.put(psninfo.getPostcode(), psninfo);
                        }
                    }*/


                    //=====2、遍历组织json数组做相应操作
                    for (int i = 0; i < orgResultJsonArray.size(); i++) {
                        NccPostV nccPostV = new NccPostV();
                        nccPostV.setDeptname(orgResultJsonArray.getJSONObject(i).getString("deptname"));
                        nccPostV.setOrgname(orgResultJsonArray.getJSONObject(i).getString("orgname"));
                        nccPostV.setPkDept(orgResultJsonArray.getJSONObject(i).getString("pk_dept"));
                        nccPostV.setPkOrg(orgResultJsonArray.getJSONObject(i).getString("pk_org"));
                        nccPostV.setPkPost(orgResultJsonArray.getJSONObject(i).getString("pk_post"));
                        nccPostV.setPostcode(orgResultJsonArray.getJSONObject(i).getString("postcode"));
                        nccPostV.setPostname(orgResultJsonArray.getJSONObject(i).getString("postname"));

                        add++;
                        nccPostVService.itriptxAddNccPostV(nccPostV);
                       /* if (!psnMap.containsKey(nccPostV.getPostcode())) {
                            // 不存在的 add
                            add++;
                            nccPostVService.itriptxAddNccPostV(nccPostV);
                        } else {
                            // 存在的 修改
                            modify++;
                            nccPostVService.itriptxModifyNccPostV(nccPostV);
                            //在同步表删除已修改过的
                            psnMap.remove(nccPostV.getPostcode());
                        }*/
                    }
                    //剩下未修改的进行删除
                    /*if (psnMap.size() != 0 && null != psnMap) {

                        Set<Map.Entry<String, Object>> entries = psnMap.entrySet();
                        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
                        while (iterator.hasNext()) {
                            nccPostVService.itriptxDeleteNccPostVById(((NccPostV) iterator.next().getValue()).getId());
                            del++;
                        }
                    }*/
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(JSON.parseObject(orgResult).getString("message"));
            }
            //接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_post_v");
            ncclog.setContent(requstBody);
            ncclog.setName("岗位视图同步成功" + "添加" + add + "修改" + modify + "删除" + del);
            ncclog.setResultLong(orgResult);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        } catch (Exception e) {
            System.out.println("岗位视图同步错误");
            e.printStackTrace();

            //接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_post_v");
            ncclog.setContent("");
            ncclog.setName("岗位视图同步错误");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);
            System.out.println("岗位同步错误" + e.getMessage());
        }
    }

    @Override
    @Scheduled(cron = "0 8 4 * * ?")
    public void hrpsnclv() throws Exception {
        try {
            //=====1、请求地址获取岗位
            String requstBody = "{\"view\":\"hr_psncl_v\"}";
            String orgResult = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            JSONArray orgResultJsonArray = JSON.parseObject(orgResult).getJSONArray("data");

            int add = 0;
            //是否成功
            if (JSON.parseObject(orgResult).getIntValue("code") == 1) {
                if (null != orgResultJsonArray.toJSONString() && !orgResultJsonArray.toJSONString().equals("[]")) {
                    //清空表
                    viewService.truncateTable("ncc_psncl_v");
                    //=====2、遍历组织json数组做相应操作
                    for (int i = 0; i < orgResultJsonArray.size(); i++) {

                        NccPsnclV nccPsnclV = JSON.toJavaObject(orgResultJsonArray.getJSONObject(i), NccPsnclV.class);
                        nccPsnclV.setPostcode(orgResultJsonArray.getJSONObject(i).get("code").toString());
                        nccPsnclV.setPostname(orgResultJsonArray.getJSONObject(i).get("name").toString());
                        nccPsnclVService.itriptxAddNccPsnclV(nccPsnclV);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(JSON.parseObject(orgResult).getString("message"));
            }

            //=====3、成功

            //接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_psncl_v");
            ncclog.setContent(requstBody);
            ncclog.setName("人员类别视图同步成功清空并添加" + add);
            ncclog.setResultLong(orgResult);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        } catch (Exception e) {
            System.out.println("人员类别视图同步失败");
            e.printStackTrace();
            //=====、失败

            //接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_psncl_v");
            ncclog.setContent("");
            ncclog.setName("人员类别视图同步失败");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }


    @Override
    @Scheduled(cron = "0 9 4 * * ?")
    public void querypsndoc() throws Exception {
        try {
            String requstBody = "{\"view\":\"bd_psndoc_zz_v \"}";
            int add = 0, modify = 0, del = 0;
            String result = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            JSONObject resultJson = JSONObject.parseObject(result);

            if (resultJson.getIntValue("code") == 1) {
                if (null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {

                    //清空表
                    viewService.truncateTable("bd_psndoc_zz_v");
                    /*List<BdPsndocZzV> psninfoList = bdPsndocZzVService.getBdPsndocZzVListByMap(null);
                    Map<String, Object> psnMap = new HashMap<>();
                    if (null != psninfoList && psninfoList.size() != 0) {
                        for (BdPsndocZzV psninfo : psninfoList) {
                            psnMap.put(psninfo.getCode(), psninfo);
                        }
                    }*/
                    JSONArray dataArray = resultJson.getJSONArray("data");
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jsonObject = resultJson.getJSONArray("data").getJSONObject(i);
                        BdPsndocZzV bdPsndocZzV = new BdPsndocZzV();
                        bdPsndocZzV.setPostname(jsonObject.getString("postname"));
                        bdPsndocZzV.setBdPsndocZzVId(jsonObject.getString("id"));
                        bdPsndocZzV.setClerkcode(jsonObject.getString("clerkcode"));
                        bdPsndocZzV.setCode(jsonObject.getString("code"));
                        bdPsndocZzV.setDeptName(jsonObject.getString("dept_name"));
                        bdPsndocZzV.setIdtype(jsonObject.getString("idtype"));
                        bdPsndocZzV.setIsmainjob(jsonObject.getString("ismainjob"));
                        bdPsndocZzV.setName(jsonObject.getString("name"));
                        bdPsndocZzV.setOrgName(jsonObject.getString("org_name"));
                        bdPsndocZzV.setPkDept(jsonObject.getString("pk_dept"));
                        bdPsndocZzV.setPkOrg(jsonObject.getString("pk_org"));
                        bdPsndocZzV.setPkPsncl(jsonObject.getString("pk_psncl"));
                        bdPsndocZzV.setPkPsndoc(jsonObject.getString("pk_psndoc"));
                        bdPsndocZzV.setPkPsnjob(jsonObject.getString("pk_psnjob"));
                        bdPsndocZzV.setPkPsnorg(jsonObject.getString("pk_psnorg"));
                        bdPsndocZzV.setPkPost(jsonObject.getString("pk_post"));
                        add++;
                        bdPsndocZzVService.itriptxAddBdPsndocZzV(bdPsndocZzV);
                        /*if (!psnMap.containsKey(bdPsndocZzV.getCode())) {
                            // 不存在的 add
                            add++;
                            bdPsndocZzVService.itriptxAddBdPsndocZzV(bdPsndocZzV);
                        } else {
                            // 存在的 修改
                            modify++;
                            bdPsndocZzVService.itriptxModifyBdPsndocZzV(bdPsndocZzV);
                            //在同步表删除已修改过的
                            psnMap.remove(bdPsndocZzV.getCode());
                        }*/
                    }
                    //剩下未修改的进行删除
                    /*if (psnMap.size() != 0 && null != psnMap) {

                        Set<Map.Entry<String, Object>> entries = psnMap.entrySet();
                        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
                        while (iterator.hasNext()) {
                            bdPsndocZzVService.itriptxDeleteBdPsndocZzVById(((BdPsndocZzV) iterator.next().getValue()).getId());
                            del++;
                        }
                    }*/
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(resultJson.getString("message"));
            }


            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("bd_psndoc_zz_v");
            ncclog.setContent(requstBody);
            ncclog.setName("待转正人员视图添加成功添加" + add + "修改" + modify + "删除" + del);
            ncclog.setResultLong(result);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);
        } catch (Exception e) {
            System.out.println("待转正人员视图false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("bd_psndoc_zz_v");
            ncclog.setContent("");
            ncclog.setName("待转正人员视图false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        }
    }

    @Override
    @Scheduled(cron = "0 10 4 * * ?")
    public void hrPostseriesV() throws Exception {
        try {
            //=====1、请求地址获取岗位
            String requstBody = "{\"view\":\"hr_postseries_v\"}";
            String orgResult = nccloudService.sendApi(nccloudService.queryViewUrl, requstBody);
            JSONArray orgResultJsonArray = JSON.parseObject(orgResult).getJSONArray("data");

            int add = 0;

            //是否成功
            if (JSON.parseObject(orgResult).getIntValue("code") == 1) {
                if (null != orgResultJsonArray.toJSONString() && !orgResultJsonArray.toJSONString().equals("[]")) {
                    //清空表
                    viewService.truncateTable("ncc_postseries_v");
                    //=====2、遍历组织json数组做相应操作
                    for (int i = 0; i < orgResultJsonArray.size(); i++) {

                        NccPostseriesV nccPostseriesV = new NccPostseriesV();
                        nccPostseriesV.setPkGroup(orgResultJsonArray.getJSONObject(i).getString("pk_group"));
                        nccPostseriesV.setPkOrg(orgResultJsonArray.getJSONObject(i).getString("pk_org"));
                        nccPostseriesV.setPkPostseries(orgResultJsonArray.getJSONObject(i).getString("pk_postseries"));
                        nccPostseriesV.setPostseriescode(orgResultJsonArray.getJSONObject(i).getString("postseriescode"));
                        nccPostseriesV.setPostseriesname(orgResultJsonArray.getJSONObject(i).getString("postseriesname"));
                        nccPostseriesVService.itriptxAddNccPostseriesV(nccPostseriesV);
                        add++;
                    }
                } else {
                    throw new RuntimeException("请求NC视图data-null");
                }
            } else {
                throw new RuntimeException(JSON.parseObject(orgResult).getString("message"));
            }

            //=====3、成功

            //接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_postseries_v");
            ncclog.setContent(requstBody);
            ncclog.setName("新岗位序列视图同步成功清空并添加" + add);
            ncclog.setResultLong(orgResult);
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);

        } catch (Exception e) {
            System.out.println("新岗位序列视图同步失败");
            e.printStackTrace();
            //=====、失败


            //接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hr_postseries_v");
            ncclog.setContent("");
            ncclog.setName("新岗位序列视图同步失败");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);
        }
    }

    @Override
    @Scheduled(cron = "0 11 4 * * ?")
    public void querypsndoc1() throws Exception {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pk_group","0");
            /*jsonObject.put("pk_org","");
            jsonObject.put("pk_dept","");
            jsonObject.put("code","");
            jsonObject.put("name","");
            jsonObject.put("pk_psndoc","");
            jsonObject.put("id","");
            jsonObject.put("indocflag","");
            jsonObject.put("ts_begin","");
            jsonObject.put("ts_end","");*/
            String requstBody=jsonObject.toJSONString();
            int add = 0, modify = 0, del = 0;
            String result = nccloudService.sendApi(nccloudService.queryPsndoctUrl, requstBody);
            JSONObject resultJson = JSONObject.parseObject(result);


            //判断是返回值否正确
            if (resultJson.getIntValue("code") == 1 && null != resultJson.getJSONArray("data").toJSONString() && !resultJson.getJSONArray("data").toJSONString().equals("[]")) {

                //清空表
                viewService.truncateTable("ncc_psninfo");


                //解析人员信息提取数据
                JSONArray dataArray = resultJson.getJSONArray("data");
                a:
                for (int i = 0; i < dataArray.size(); i++) {


                    NccPsninfo nccPsninfo = new NccPsninfo();
                    JSONObject psndoc = dataArray.getJSONObject(i);
                    JSONObject psninfo = psndoc.getJSONObject("psninfo"); //人员基本信息
                    JSONArray jobArray = psndoc.getJSONArray("psninfo_job"); //基本工作信息
                    JSONArray jobArray_hipsninfo_job = psndoc.getJSONArray("hipsninfo_job");//人力基本工作信息


                    /**
                     * 人力工作记录
                     */
                    if (null != jobArray_hipsninfo_job) {
                        //遍历人力基本工作信息判断职位是否为主职，是否在岗、记录是否最新
                        for (int a = 0; a < jobArray_hipsninfo_job.size(); a++) {

                            //判断人力工作记录是否最新
                            if (null != jobArray_hipsninfo_job.getJSONObject(a).getString("lastflag") && jobArray_hipsninfo_job.getJSONObject(a).getString("lastflag").equals("Y")) {


                                //判断取值是否为空则跳过
                                String ismainjob = null;
                                String poststat = null;
                                try {
                                    ismainjob = jobArray_hipsninfo_job.getJSONObject(a).getString("ismainjob");
                                    poststat = jobArray_hipsninfo_job.getJSONObject(a).getString("poststat");
                                    if (null == ismainjob || null == poststat) {
                                        throw new Exception();
                                    }
                                } catch (Exception e) {
                                    continue;
                                }

                                if (ismainjob.equals("Y") && poststat.equals("Y")) {


                                    JSONObject jobArray_hipsninfo_jobJSONObject = jobArray_hipsninfo_job.getJSONObject(a);
                                    nccPsninfo.setJobglbdef2(jobArray_hipsninfo_jobJSONObject.getString("jobglbdef2"));//任现职时间
                                    nccPsninfo.setJobglbdef4(jobArray_hipsninfo_jobJSONObject.getString("jobglbdef4"));//任现职级时间

                                    if (jobArray_hipsninfo_jobJSONObject.containsKey("pk_post")) {
                                        nccPsninfo.setPkPost(jobArray_hipsninfo_jobJSONObject.getJSONObject("pk_post").getString("pk"));//岗位主键
                                    }

                                    if (jobArray_hipsninfo_jobJSONObject.containsKey("pk_postseries")) {
                                        nccPsninfo.setPkPostseries(jobArray_hipsninfo_jobJSONObject.getJSONObject("pk_postseries").getString("pk"));//岗位序列主键
                                    }

                                    if (jobArray_hipsninfo_jobJSONObject.containsKey("jobglbdef3")) {
                                        nccPsninfo.setJobglbdef3Name(jobArray_hipsninfo_jobJSONObject.getJSONObject("jobglbdef3").getString("name"));//行政级别名称
                                        nccPsninfo.setJobglbdef3(jobArray_hipsninfo_jobJSONObject.getJSONObject("jobglbdef3").getString("pk"));//行政级别pk
                                    }

                                    /**
                                     * 人员信息
                                     */
                                    if (null != psninfo) {
                                        /**
                                         * 人员对象
                                         */
                                        nccPsninfo.setCode(psninfo.getString("code").trim());
                                        nccPsninfo.setName(psninfo.getString("name"));
                                        nccPsninfo.setCreationtime(psninfo.getString("creationtime"));
                                        nccPsninfo.setDr(psninfo.getInteger("dr"));
                                        nccPsninfo.setEnablestate(psninfo.getInteger("enablestate"));
                                        nccPsninfo.setBirthdate(psninfo.getString("birthdate"));
                                        nccPsninfo.setSex(psninfo.getInteger("sex"));
                                        nccPsninfo.setMobile(psninfo.getString("mobile"));
                                        nccPsninfo.setPkPsndoc(psninfo.getString("pk_psndoc"));
                                        nccPsninfo.setPkGroup(psninfo.getJSONObject("pk_group").getString("pk"));
                                        nccPsninfo.setPkGroupCode(psninfo.getJSONObject("pk_group").getString("code"));
                                        try {
                                            nccPsninfo.setJoinworkdate(psninfo.getString("joinworkdate"));
                                        } catch (Exception e) {
                                            nccPsninfo.setJoinworkdate(null);
                                        }
                                        //设置组织
                                        nccPsninfo.setPkOrg(psninfo.getJSONObject("pk_org").getString("pk"));
                                        nccPsninfo.setPkOrgCode(psninfo.getJSONObject("pk_org").getString("code"));
                                        nccPsninfo.setPkOrgName(psninfo.getJSONObject("pk_org").getString("name"));

                                    } else {
                                        continue a;
                                    }

                                    /**
                                     * 基础工作记录
                                     */
                                    if (null != jobArray) {
                                        //取最新的入职日期
                                        Map<Long, Integer> map = new HashMap<>();
                                        //遍历人员基本工作信息
                                        for (int b = 0; b < jobArray.size(); b++) {
                                            JSONObject job = jobArray.getJSONObject(b);
                                            map.put(sdf1.parse(job.getString("indutydate")).getTime(), b);

                                        }


                                        Set<Map.Entry<Long, Integer>> entries = map.entrySet();
                                        List<Map.Entry<Long, Integer>> entryArrayList = new ArrayList<>(entries);
                                        //判断是否只有一条信息
                                        if (entryArrayList.size() > 1) {

                                            Collections.sort(entryArrayList, new Comparator<Map.Entry<Long, Integer>>() {
                                                @Override
                                                public int compare(Map.Entry<Long, Integer> o1, Map.Entry<Long, Integer> o2) {
                                                    return (int) (o2.getKey() - o1.getKey());
                                                }
                                            });
                                        }

                                        JSONObject job = jobArray.getJSONObject(entryArrayList.get(0).getValue());
                                        //设置职位类型
                                        nccPsninfo.setPkPsncl(job.getJSONObject("pk_psncl").getString("pk"));
                                        nccPsninfo.setPkPsnclCode(job.getJSONObject("pk_psncl").getString("code"));
                                        nccPsninfo.setPkPsnclName(job.getJSONObject("pk_psncl").getString("name"));
                                        //设置人员任职时间
                                        nccPsninfo.setIndutydate(job.getString("indutydate"));
                                        nccPsninfo.setEnddutydate(job.getString("enddutydate"));

                                        //设置部门
                                        nccPsninfo.setPkDept(job.getJSONObject("pk_dept").getString("pk"));
                                        nccPsninfo.setPkDeptCode(job.getJSONObject("pk_dept").getString("code"));
                                        nccPsninfo.setPkDeptName(job.getJSONObject("pk_dept").getString("name"));

                                        if (job.containsKey("pk_job")) {
                                            nccPsninfo.setPkJob(job.getJSONObject("pk_job").getString("pk"));//职务pk
                                            nccPsninfo.setPkJobName(job.getJSONObject("pk_job").getString("name"));//职务名称
                                        }
                                    }

                                    add++;
                                    psndocService.savePsn(nccPsninfo);

                                    break;
                                }
                            }
                        }
                    }
                }
            } else {
                throw new RuntimeException("data-null");
            }

           /* if(result.length()<100000){
                // 接口调用日志保存
                NCCInterfaceLog ncclog = new NCCInterfaceLog();
                ncclog.setBusinessNo("hrorg");
                ncclog.setContent(requstBody);
                ncclog.setName("HR人员同步"+"新增人员：" + add + ";修改人员：" + modify);
                ncclog.setResultLong(result);
                ncclog.setState("1");
                ncclog.setDisposeState("0");
                logService.save(ncclog);
            }*/
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("ncc_psninfo");
            ncclog.setContent(requstBody);
            ncclog.setName("HR人员视图同步" + "新增人员：" + add + ";修改人员：" + modify + ";删除人员：" + del);
            ncclog.setResultLong("");
            ncclog.setState("1");
            ncclog.setDisposeState("0");
            logService.save(ncclog);


        } catch (Exception e) {
            System.out.println("HR人员视图同步false");
            e.printStackTrace();
            // 接口调用日志保存
            NCCInterfaceLog ncclog = new NCCInterfaceLog();
            ncclog.setBusinessNo("hrorg");
            ncclog.setContent("");
            ncclog.setName("HR人员视图同步false");
            ncclog.setResultLong(e.getMessage());
            ncclog.setState("0");
            ncclog.setDisposeState("0");
            logService.save(ncclog);
        }
    }

}
